<template>
  <el-container>
    <el-header :height="headHeight" style="padding-top: 10px;">
      <el-form label-width="100px" label-position="left">
        <el-form-item label="部门名称：">
          <el-input v-model="SelectDeptName" clearable placeholder="请输入部门名称" style="width:400px"
            @keyup.enter.native="SelectFrom" @clear="SelectFrom" />
        </el-form-item>
        <el-form-item label="状态：">
          <el-radio-group v-model="SelectStatus" @change="Radio_Change">
            <el-radio-button label="-1">全部</el-radio-button>
            <el-radio-button label="1">启用</el-radio-button>
            <el-radio-button label="0">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建日期：">
          <el-date-picker v-model="SelectStartCreate" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" style="width:400px" @change="SelectFrom" />
        </el-form-item>
        <el-button v-if="btnAip.add.buttonCaption" type="primary" @click="Addfrom">
          {{ btnAip.add.buttonCaption }}</el-button>
        <el-button v-if="btnAip.query.buttonCaption" type="primary" @click="SelectFrom">
          {{ btnAip.query.buttonCaption }}</el-button>
      </el-form>
    </el-header>
    <el-main>
      <el-table ref="roleTable" fixed :data="tableData" border highlight-current-row :height="mainHeight"
        :default-sort="{ prop: 'createTime', order: 'descending' }" @sort-change="Sort_Change">
        <el-table-column type="index" width="50" />
        <el-table-column prop="deptName" label="部门名称" fit sortable />
        <el-table-column prop="deptDesc" label="部门说明" width="200" />
        <el-table-column prop="upDeptName" label="上级部门" width="100" />
        <el-table-column label="部门状态" show-overflow-tooltip width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == true" type="success">启用</el-tag>
            <el-tag v-if="scope.row.status == false" type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" :formatter="dateFormat" width="160" sortable />
        <el-table-column prop="createName" label="创建人" width="80" />
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="light"  content="编辑数据" placement="top">
            <el-button v-if="btnAip.edit.buttonCaption" icon="el-icon-edit" circle
              @click="Updatefrom(scope.$index, scope.row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="light" content="删除数据" placement="top">
            <el-button v-if="btnAip.delete.buttonCaption" icon="el-icon-delete" type="danger" circle
              @click="SelectDelete(scope.$index, scope.row)" />
           </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer :height="footHeight">
      <el-pagination background layout="prev, pager, next" :total="this.DateCount" :page-size="this.data.pageSize"
        :current-page="dateIndex" @current-change="Current_Change" />
    </el-footer>

    <el-dialog :title="dialogFormTitle" :visible.sync="dialogFormVisible" width="30%">
      <el-form ref="roleFrom" :model="dataInfo" :rules="rules">
        <el-form-item label="部门名称：" :label-width="formLabelWidth" prop="deptName">
          <el-input v-model="dataInfo.deptName" autocomplete="off" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门说明：" :label-width="formLabelWidth">
          <el-input v-model="dataInfo.deptDesc" autocomplete="off" placeholder="请输入部门说明" />
        </el-form-item>
        <el-form-item label="上级部门：" :label-width="formLabelWidth">
          <el-select v-model="dataInfo.pid" placeholder="请选择">
            <el-option v-for="item in deptOptions" :key="item.id" :label="item.deptName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态：" :label-width="formLabelWidth">
          <el-switch v-model="dataInfo.status" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="SaveFrom">保存</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>
<script>
import axios_request from '@/utils/request'
import DateUtil from '@/utils/dateUtil'
import height from '@/utils/height'
import { getBtnCtr } from '@/utils/BtnControl'
export default {
  name: "Department",
  data() {
    return {
      btnAip: '',
      rules: {
        deptName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度需要在2到30个字符', trigger: 'blur' }
        ]
      },
      headHeight: '200px',
      footHeight: '50px',
      mainHeight: '',
      tableData: [],
      radio: '1',
      dialogFormVisible: false, // 弹出框
      dialogFormTitle: '',
      formLabelWidth: '120px',
      DateCount: 0,
      dateIndex: 1,
      SelectDeptName: '',
      SelectStatus: '-1',
      SelectStartCreate: '',
      SelectSort: '',
      data: {
        isPaging: true,
        pageSize: 25,
        pageIndex: 1,
        postData: null,
        postDataList: null,
        queryConditions: null,
        orderByConditions: null
      },
      dataInfo: {
        id: 0,
        roleName: '',
        status: true,
        roleDesc: '',
        createTime: '',
        createId: 0,
        tUsersUserName: '',
        pid:undefined
      },
      SelectRow: null,
      SelectRowCount: 0,
      deptOptions: []
    }
  },
  watch: {
    tableData() {
      if (this.dateIndex > 1 && this.tableData.length == []) {
        this.dateIndex--
        // 初始化表格数据
        this.SelectFrom()
      }
    }
  },
  created: function () {
    // 动态头部按钮
    this.btnAip = getBtnCtr(
      this.$route.path,
      this.$store.getters.userPermission
    )
    this.mainHeight = height - 126 - parseInt(this.headHeight) - parseInt(this.footHeight).toString() + 'px'
    this.SelectFrom()
    this.GetDeptOptions();
  },
  methods: {
    GetDeptOptions() {
      let query = {
        isPaging: false,
        pageSize: 25,
        pageIndex: this.dateIndex,
        postData: null,
        postDataList: null,
        queryConditions: null,
        orderByConditions: null
      }
      axios_request({
        method: 'GET',
        url: '/api/Tpmdept',
        params: { requestObject: JSON.stringify(query) }
      }).then(response => {
        this.deptOptions = response.data
      }).catch(error => console.log(error))

    },
    SelectFrom() {
      this.data = {
        isPaging: true,
        pageSize: 25,
        pageIndex: this.dateIndex,
        postData: null,
        postDataList: null,
        queryConditions: null,
        orderByConditions: null
      }
      var arrayObj = new Array()
      if (this.SelectDeptName != '') {
        arrayObj.push({
          column: 't.deptName',
          condition: 6,
          content: this.SelectDeptName
        })
      }
      if (this.SelectStatus != '-1') {
        arrayObj.push({
          column: 't.status',
          condition: 0,
          content: this.SelectStatus
        })
      }
      if (this.SelectSort.prop != null) {
        this.data.orderByConditions = [
          {
            column: this.SelectSort.prop,
            condition: this.SelectSort.order == 'descending' ? 'DESC' : 'ASC'
          }
        ]
      }
      if (this.SelectStartCreate && this.SelectStartCreate.length > 0) {
        arrayObj.push({
          column: 't.createTime',
          content:
            DateUtil.Format(this.SelectStartCreate[0], 'yyyy-MM-dd') +
            ',' +
            DateUtil.Format(this.SelectStartCreate[1], 'yyyy-MM-dd'),
          condition: 10
        })
      }
      this.data.queryConditions = arrayObj
      axios_request({
        method: 'GET',
        url: '/api/Tpmdept',
        params: { requestObject: JSON.stringify(this.data) }
      })
        .then(response => {
          this.tableData = response.data
          this.DateCount = response.totalNumber
        })
        .catch(error => console.log(error))
    },
    Addfrom() {
      this.dialogFormTitle = '新增部门'
      this.dialogFormVisible = true
      this.dataInfo = {
        id: 0,
        deptName: '',
        status: true,
        deptDesc: '',
        createTime: new Date(),
        createId: 0,
        tUsersUserName: '',
        pid:undefined
      }
    },
    Updatefrom(_Index, _Row) {
      this.dialogFormTitle = '编辑部门'
      this.dialogFormVisible = true
      this.dataInfo.id = _Row.id
      this.dataInfo.deptName = _Row.deptName
      this.dataInfo.deptDesc = _Row.deptDesc
      this.dataInfo.status = _Row.status
      this.dataInfo.createTime = _Row.createTime
      this.dataInfo.createId = _Row.createId
      this.dataInfo.pid = _Row.pid
    },
    SelectDelete(_Index, _Row) {
      this.$confirm('是否确定并删除该部门信息?', '确认对话框', {
        distinguishCancelAndClose: true,
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(_ => {
          this.data = {
            isPaging: true,
            pageSize: 10,
            pageIndex: 1,
            postData: _Row,
            postDataList: null,
            queryConditions: null,
            orderByConditions: null
          }
          axios_request({
            method: 'DELETE',
            url: '/api/Tpmdept',
            data: this.data
          }).then(response => {
              this.SelectFrom()
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            })
            .catch(error => console.log(error))
        })
        .catch(_ => { })
    },
    Status(_Index, _Row) {
      if (_Row.status) {
        this.$confirm('是否禁用此部门?', '提示', {
          distinguishCancelAndClose: true,
          type: 'warning',
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        }).then(_ => {
          _Row.status = false
          this.dataInfo = _Row
          this.data.postData = this.dataInfo // 主表给对象
          axios_request({
            method: 'PUT',
            url: '/api/Tpmdept',
            data: this.data
          })
            .then(response => {
              this.SelectFrom()
              this.$message({
                message: '状态修改成功',
                type: 'success'
              })
              this.dialogFormVisible = false
            })
        })
      } else {
        _Row.status = true
        this.dataInfo = _Row
        this.data.postData = this.dataInfo // 主表给对象
        axios_request({
          method: 'PUT',
          url: '/api/Tpmdept',
          data: this.data
        })
          .then(response => {
            this.SelectFrom()
            this.$message({
              message: '状态修改成功',
              type: 'success'
            })
            this.dialogFormVisible = false
          })
          .catch(error => {

          })
      }
    },
    SaveFrom() {
      // ref="roleFrom"验证这一区域
      this.$refs['roleFrom'].validate(valid => {
        if (valid) {
          this.data.postData = this.dataInfo // 主表给对象
          axios_request({
            method: this.dataInfo.id > 0 ? 'PUT' : 'POST',
            url: '/api/Tpmdept',
            data: this.data
          })
            .then(response => {
              this.SelectFrom()
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.dialogFormVisible = false
            })
        } else {
          return false
        }
      })
    },
    Current_Change(val) {
      this.dateIndex = val
      this.SelectFrom()
    },
    Radio_Change() {
      this.SelectFrom()
    },
    dateFormat(row, column, cellValue, index) {
      var date = row[column.property]

      var date1 = new Date(+new Date(date) + 8 * 3600 * 1000)
        .toISOString()
        .replace(/T/g, ' ')
        .replace(/\.[\d]{3}Z/, '')
      return date1
    },
    Sort_Change(row) {
      this.SelectSort = row
      this.SelectFrom()
    }
  }
}
</script>
